<template>
  <div class="history-list">
    <div class="history-header">
      <h3 class="history-title">
        <span class="title-icon">📚</span>
        解码历史
        <span class="history-count">({{ history.length }})</span>
      </h3>
      <div class="header-actions">
        <a-button 
          v-if="history.length > 0" 
          @click="clearHistory" 
          type="text" 
          danger
          size="small"
        >
          <template #icon>
            <DeleteOutlined />
          </template>
          清空历史
        </a-button>
      </div>
    </div>
    
    <div v-if="history.length === 0" class="empty-history">
      <div class="empty-icon">
        <HistoryOutlined />
      </div>
      <p class="empty-text">暂无解码历史</p>
      <p class="empty-hint">解码成功的二维码会自动保存在这里</p>
    </div>
    
    <div v-else class="history-items">
      <div 
        v-for="item in sortedHistory" 
        :key="item.id"
        class="history-item"
        :class="{ active: selectedId === item.id }"
        @click="selectHistory(item)"
      >
        <div class="item-header">
          <div class="item-meta">
            <a-tag :color="getTypeColor(item.type)" size="small" class="type-tag">
              {{ getTypeName(item.type) }}
            </a-tag>
            <span class="item-source">
              <component :is="getSourceIcon(item.source)" class="source-icon" />
              {{ getSourceName(item.source) }}
            </span>
          </div>
          <span class="item-time">{{ formatTime(item.timestamp) }}</span>
        </div>
        
        <div class="item-content">
          <div class="content-preview">
            {{ truncateContent(item.content) }}
          </div>
        </div>
        
        <div class="item-actions">
          <a-button 
            @click.stop="copyContent(item.content)" 
            type="text" 
            size="small"
            class="action-btn"
          >
            <template #icon>
              <CopyOutlined />
            </template>
          </a-button>
          
          <a-button 
            v-if="item.type === 'url'" 
            @click.stop="openUrl(item.content)" 
            type="text" 
            size="small"
            class="action-btn"
          >
            <template #icon>
              <LinkOutlined />
            </template>
          </a-button>
          
          <a-button 
            @click.stop="deleteItem(item.id)" 
            type="text" 
            size="small"
            danger
            class="action-btn"
          >
            <template #icon>
              <DeleteOutlined />
            </template>
          </a-button>
        </div>
      </div>
    </div>
    
    <!-- 分页 -->
    <div v-if="history.length > pageSize" class="history-pagination">
      <a-pagination
        v-model:current="currentPage"
        :total="history.length"
        :page-size="pageSize"
        :show-size-changer="false"
        :show-quick-jumper="false"
        :show-total="(total, range) => `${range[0]}-${range[1]} 共 ${total} 条`"
        size="small"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { message, Modal } from 'ant-design-vue'
import {
  DeleteOutlined,
  CopyOutlined,
  LinkOutlined,
  HistoryOutlined,
  CameraOutlined,
  PictureOutlined
} from '@ant-design/icons-vue'
import { DecodeResult, QrCodeType } from '../utils/qrDecoder'

// 定义属性
interface Props {
  history: DecodeResult[]
}

const props = defineProps<Props>()

// 定义事件
const emit = defineEmits<{
  'select-history': [result: DecodeResult]
  'clear-history': []
}>()

// 响应式数据
const selectedId = ref<string | null>(null)
const currentPage = ref(1)
const pageSize = 10

// 计算属性
const sortedHistory = computed(() => {
  const sorted = [...props.history].sort((a, b) => b.timestamp - a.timestamp)
  const start = (currentPage.value - 1) * pageSize
  const end = start + pageSize
  return sorted.slice(start, end)
})

// 获取类型颜色
const getTypeColor = (type: QrCodeType): string => {
  const colorMap = {
    [QrCodeType.URL]: 'blue',
    [QrCodeType.TEXT]: 'green',
    [QrCodeType.WIFI]: 'orange',
    [QrCodeType.VCARD]: 'purple',
    [QrCodeType.EMAIL]: 'cyan',
    [QrCodeType.PHONE]: 'magenta',
    [QrCodeType.SMS]: 'lime',
    [QrCodeType.UNKNOWN]: 'default'
  }
  return colorMap[type] || 'default'
}

// 获取类型名称
const getTypeName = (type: QrCodeType): string => {
  const nameMap = {
    [QrCodeType.URL]: '网址',
    [QrCodeType.TEXT]: '文本',
    [QrCodeType.WIFI]: 'WiFi',
    [QrCodeType.VCARD]: '联系人',
    [QrCodeType.EMAIL]: '邮箱',
    [QrCodeType.PHONE]: '电话',
    [QrCodeType.SMS]: '短信',
    [QrCodeType.UNKNOWN]: '未知'
  }
  return nameMap[type] || '未知'
}

// 获取来源图标
const getSourceIcon = (source: 'upload' | 'camera') => {
  return source === 'upload' ? PictureOutlined : CameraOutlined
}

// 获取来源名称
const getSourceName = (source: 'upload' | 'camera'): string => {
  return source === 'upload' ? '图片' : '摄像头'
}

// 格式化时间
const formatTime = (timestamp: number): string => {
  const now = Date.now()
  const diff = now - timestamp
  
  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  } else if (diff < 604800000) {
    return `${Math.floor(diff / 86400000)}天前`
  } else {
    return new Date(timestamp).toLocaleDateString('zh-CN')
  }
}

// 截断内容
const truncateContent = (content: string): string => {
  const maxLength = 80
  if (content.length <= maxLength) {
    return content
  }
  return content.substring(0, maxLength) + '...'
}

// 选择历史记录
const selectHistory = (result: DecodeResult) => {
  selectedId.value = result.id
  emit('select-history', result)
}

// 复制内容
const copyContent = async (content: string) => {
  try {
    await navigator.clipboard.writeText(content)
    message.success('内容已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    message.error('复制失败，请手动复制')
  }
}

// 打开链接
const openUrl = (content: string) => {
  try {
    window.open(content, '_blank')
  } catch (error) {
    console.error('打开链接失败:', error)
    message.error('无法打开链接')
  }
}

// 删除单个记录
const deleteItem = (id: string) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这条解码记录吗？',
    okText: '删除',
    okType: 'danger',
    cancelText: '取消',
    onOk() {
      // 这里需要通过事件通知父组件删除
      // 由于当前设计中没有单独删除的接口，这里先用message提示
      message.info('单条删除功能待实现')
    }
  })
}

// 清空历史记录
const clearHistory = () => {
  Modal.confirm({
    title: '确认清空',
    content: '确定要清空所有解码历史吗？此操作不可恢复。',
    okText: '清空',
    okType: 'danger',
    cancelText: '取消',
    onOk() {
      emit('clear-history')
    }
  })
}
</script>

<style scoped>
.history-list {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.history-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-icon {
  font-size: 16px;
}

.history-count {
  font-size: 14px;
  color: #8c8c8c;
  font-weight: 400;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.empty-history {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
  color: #8c8c8c;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-text {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 8px 0;
  color: #1a1a1a;
}

.empty-hint {
  font-size: 14px;
  margin: 0;
  line-height: 1.5;
}

.history-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 400px;
  overflow-y: auto;
}

.history-item {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  padding: 16px;
  background: #fafafa;
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
}

.history-item:hover {
  border-color: #667eea;
  background: #f9f9ff;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
}

.history-item.active {
  border-color: #667eea;
  background: #f0f4ff;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.item-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.type-tag {
  font-weight: 500;
}

.item-source {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #8c8c8c;
}

.source-icon {
  font-size: 12px;
}

.item-time {
  font-size: 12px;
  color: #8c8c8c;
}

.item-content {
  margin-bottom: 12px;
}

.content-preview {
  font-size: 14px;
  color: #1a1a1a;
  line-height: 1.4;
  word-break: break-all;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-actions {
  display: flex;
  gap: 4px;
  justify-content: flex-end;
}

.action-btn {
  width: 28px;
  height: 28px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}

.action-btn:hover {
  background-color: rgba(0, 0, 0, 0.04);
}

.history-pagination {
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: center;
}

/* 滚动条样式 */
.history-items::-webkit-scrollbar {
  width: 6px;
}

.history-items::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.history-items::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.history-items::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .history-list {
    padding: 16px;
  }
  
  .history-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .history-title {
    font-size: 16px;
  }
  
  .history-item {
    padding: 12px;
  }
  
  .item-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .item-meta {
    flex-wrap: wrap;
  }
  
  .item-actions {
    justify-content: flex-start;
  }
  
  .history-items {
    max-height: 300px;
  }
}
</style>